package com.njtoyo.taxi.admin.library.jwt;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.njtoyo.taxi.admin.library.Const;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.postgresql.util.Base64;

import java.util.Date;


public abstract class JwtHelper {

    public static String parse(String token,String apiKey) {
        try{
            return parseBody(token,apiKey).getSubject();
        }catch (Exception e){
            return null;
        }
    }

    public static boolean isExpire(String token,String apiKey) {
        try{
            return DateUtil.date().isAfter(parseBody(token,apiKey).getExpiration());
        }catch (ExpiredJwtException e) {
            return true;
        }
    }

    public static Claims parseBody(String token,String apiKey){
        return Jwts.parser().setSigningKey(Base64.encodeBytes(apiKey.getBytes())).parseClaimsJws(token).getBody();
    }

    public static String build(String seed, Date expireDate,String apiKey){
        return Jwts.builder().setSubject(seed).setId(IdUtil.simpleUUID()).signWith(SignatureAlgorithm.HS256,Base64.encodeBytes(StrUtil.isBlank(apiKey)? Const.API_KEY.getBytes(): apiKey.getBytes())).setExpiration(expireDate).compact();
    }

    public static String build(String seed, Date expireDate){
        return build(seed,expireDate,null);
    }

}

